<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

Ext.onReady(function(){
	
	
	Ext.apply(Ext.form.VTypes, {
	    daterange : function(val, field) {
	        var date = field.parseDate(val);

	        if(!date){
	            return;
	        }
	        if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
	            var start = Ext.getCmp(field.startDateField);
	            start.setMaxValue(date);
	            start.validate();
	            this.dateRangeMax = date;
	        } 
	        else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
	            var end = Ext.getCmp(field.endDateField);
	            end.setMinValue(date);
	            end.validate();
	            this.dateRangeMin = date;
	        }
	        /*
	         * Always return true since we're only using this vtype to set the
	         * min/max allowed values (these are tested for after the vtype test)
	         */
	        return true;
	    },

	    password : function(val, field) {
	        if (field.initialPassField) {
	            var pwd = Ext.getCmp(field.initialPassField);
	            return (val == pwd.getValue());
	        }
	        return true;
	    },

	    passwordText : 'Passwords do not match'
	});



	var model='SaleBillVouch_import';
	var pageSize=100;
	var win;
	
	var aaa=0;
	
	var task={
			run:getState,
			interval:20000
		}
	var taskRunner=new Ext.util.TaskRunner();
	taskRunner.start(task);
		
		
    //获取状态
    //getState();
    function getState() {	
    	var stateVar={state:0};
    	Ext.Ajax.request({
		     method : 'POST',                             
		     url: Ext.ContextPath+'/getState.do',                  //发送到页面
		     success:function(request){                   //发送成功的回调函数
			       var message = request.responseText;  //取得从JSP文件out.print(...)传来的文本
			       //Ext.Msg.alert('信息',message);        //弹出对话框
			       stateVar=Ext.decode(message);
			       
			       //进行判断该显示哪个框，还是什么都不显示
			       isShow(stateVar);
		     },
		     failure:function(){                          //发送失败的回调函数
		       	Ext.Msg.alert("错误", "与后台联系的时候出现了问题");
		     },
		     params:{model:model} 
		});
		//return stateVar;
    }
    
    function isShow(stateVar) {
    	if(!stateVar.state){
    		aaa=0;
    		if(win){
    			//alert(111);
    			//这里显示不出来，还有就是页面上计算还没有做
    			
    			win.enable();
    			win.show();
    			
    			return;
    		}
    		createUploadForm();
    	} else if(stateVar.state==1){
    		aaa=0;
    		win.hide();
    		createProgress(stateVar);
    		
    		//alert('正在导入,弄个进度条');
    		
    	} else if(stateVar.state==2) {
    		aaa=0;
    		if(win){
    			win.hide();
    		}
    		grid.enable();
    		//taskRunner.stopAll();//.stop();//停止轮训
    		taskRunner.stop(task)
    		//alert('导入完成，更新grid');
    		 Ext.MessageBox.hide();
    		grid.getStore().reload()
    		
    	}else if(stateVar.state==3) {//后台发生异常的时候

    		if(win){
    			win.show();
    		} else {
    			createUploadForm();
    		}
    		
    		Ext.MessageBox.hide();
    		if(!Ext.MessageBox.isVisible()){
    			Ext.Msg.alert("错误",stateVar.msg);
    		}
    		
    		taskRunner.stop(task);
    		if(aaa==0){alert(33)
    			getState();
    			aaa++;
    		}
    		//
    		//task.interval=20000;
    		//taskRunner.start(task);
    		
    		//Ext.MessageBox.hide();
    		
    	}
    	
    }
    
    function createProgress(stateVar) {

    	if(!Ext.MessageBox.isVisible()){
    		Ext.MessageBox.show({
		    title: '请等待',
		    msg: '正在把数据导入到数据库中......',
		    width:300,
		    progress:true,
		    closable:false,
		    animEl:'id1'
		});
    	}
    	//alert(Ext.encode(stateVar));
    	
    	if(stateVar.schedule >=1){
	            Ext.MessageBox.hide();
	     }else{
	        	//alert(stateVar.schedule+"------"+schedule.msg);
	            Ext.MessageBox.updateProgress(stateVar.schedule, stateVar.msg);
	     }
    	
		
//    	var f = function(stateVar){
//	    return function(){
//	        if(stateVar.schedule >=1){
//	            Ext.MessageBox.hide();
//	        }else{
//	        	alert(stateVar.schedule+"------"+schedule.msg);
//	            Ext.MessageBox.updateProgress(stateVar.schedule, schedule.msg);
//	        }
//		   };
//		};
//		
//		f(stateVar);
//		for(var i = 1; i < 12; i++){
//		   setTimeout(f(i), i*1000);
//		}
    }
    
    //createUploadForm();
    function createUploadForm() {
    	var msg = function(title, msg){
	        Ext.Msg.show({
	            title: title,
	            msg: msg,
	            minWidth: 200,
	            modal: true,
	            icon: Ext.Msg.INFO,
	            buttons: Ext.Msg.OK
	        });
	    };
	

	    var fp = new Ext.FormPanel({
	        fileUpload: true,
	        width: 500,
	        frame: true,
	        //title: 'File Upload Form',
	        autoHeight: true,
	        bodyStyle: 'padding: 10px 10px 0 0px;',
	        labelWidth: 90,

	        labelAlign:'right',
	        defaults: {
	            anchor: '95%',
	            allowBlank: false,
	            msgTarget: 'side'
	        },
	        items: [
	        	{
	            xtype: 'hidden',
	            fieldLabel: 'model',
	            name:'model',
	            value:model
	        },{
	            xtype: 'combo',
	            fieldLabel: '专用/普通发票',
				allowBlank:false,
				editable:false,
				hiddenName:"isSpecify",
				//blankText:'',//当为空时的错误提示信息
		        triggerAction: 'all',//会使用autocomplete功能
		        valueField:'value',
		        displayField:'name',
		        selectOnFocus:true,
		        typeAhead: true,
		        width:80,
				forceSelection: true,
		        mode:'local',//从本地读取数据
		        store:new Ext.data.SimpleStore({
		              fields:['value','name'],
		              data:[['27','普通发票'],['26','专用发票']]
		       })
	        },
	        	{
	            xtype: 'fileuploadfield',
	            id: 'form-file',
	            emptyText: '选择一个excel文件',
	            fieldLabel: '文件',
	            name: 'file',
	            buttonText: '',
	            buttonCfg: {
	                iconCls: 'upload-icon'
	            }
	        }],
	        buttons: [{
	            text: '上传',
	            handler: function(){
	            	aaa=0;
	                if(fp.getForm().isValid()){
	                	
		                fp.getForm().submit({
		                    url: Ext.ContextPath+'/import.do',
		                    waitMsg: '正在上传，请稍候！',
		                    success: function(form, action){
		                    	//alert(11111);
		                       // msg('Success', 'Processed file "'+o.result.file+'" on the server');
		                    	win.hide();
		                    	
		    taskRunner.stop(task);
    		task.interval=2000;
    		taskRunner.start(task);
    		//alert(Ext.encode( action.result));
		                    	getState();
		                    },
		                    failure:function(form, action) {
		                    	switch (action.failureType) {
					            case Ext.form.Action.CLIENT_INVALID:
					                Ext.Msg.alert('错误', '请选择文件！');
					                break;
					            case Ext.form.Action.CONNECT_FAILURE:
					                Ext.Msg.alert('错误', '服务器连接错误，请联系管理员！');
					                break;
					            case Ext.form.Action.SERVER_INVALID:
					            	//alert(Ext.encode(action.result));
					                Ext.Msg.alert('错误', action.result.errors.msg);       	
					       		}
					       		
					       		//win.close();
		                    }
		                });
	                }
	            }
	        },{
	            text: '重置',
	            handler: function(){
	                fp.getForm().reset();
	            }
	        }]
	    });
	    
	    win=new Ext.Window({
	    	layout:'fit',
	    	width: 500,
	    	height:140,
	    	closeAction:'hide',
	    	closable:false,
	    	maximizable:false,
	    	minimizable:false,
	    	title:'上传文件',
	    	x:50,
	    	y:50,
	    	items:[fp]	
	    });
	    win.form=fp;
	    win.show();
    }

    function formatDate(value){
        return value ? value.dateFormat('Y-m-d') : '';
    }

    function createGrid() {
    	var cm=new Ext.grid.ColumnModel([
			new Ext.grid.RowNumberer(),//显示行号。注意当删除了某一行后，行号就不连续了，要调用grid.view.refresh();
			//new Ext.grid.CheckboxSelectionModel({handleMouseDown:Ext.emptyFn()}),增加一个复选框列
			{header:'客户编码',dataIndex:'cCusCode',sortable:true,menuDisabled:true,editor: new Ext.form.TextField({
                    allowBlank: false
                })},
			{header:'开票日期',dataIndex:'dcreatedate',sortable:true,menuDisabled:true,editor: new Ext.form.DateField({
                    format: 'Y-m-d',
                    //altFormats: 'Y-m-d',
                    allowBlank:false
                }),
                renderer:Ext.util.Format.dateRenderer('Y-m-d')
                //renderer:function(value){alert(value);return value;}
			},
			{header:'品番',dataIndex:'product_id',sortable:true,menuDisabled:true,editor: new Ext.form.TextField({
                    allowBlank: false
                })},
			
			{header:'数量',dataIndex:'quantity',sortable:true,menuDisabled:true,editor: new Ext.form.NumberField({
                    allowBlank: false
                    //allowNegative: false      
                    //maxValue: 100000
                })
			},
			{header:'不含税金额',dataIndex:'moneySui',sortable:true,menuDisabled:true,editor: new Ext.form.NumberField({
                    allowBlank: false,
                    //allowNegative: false,
                    decimalPrecision:6
                    //maxValue: 100000
                })},
			{header:'不含税单价',dataIndex:'rateUnitPrice',sortable:true,menuDisabled:true},
			{header:'sheet页的名字',dataIndex:'sheetName',sortable:false,menuDisabled:true},
			{header:'专用/普通发票',dataIndex:'isSpecify',sortable:false,menuDisabled:true,
				renderer:function(value, metaData, record, rowIndex, colIndex, store){
					if(value==27){
						return "普通发票";
					} else if(value==26){
						return "专用发票";
					} else {
						return "";	
					}
				}
			}
		]);

		//定义store
		var grid_store=new Ext.data.Store({
			autoLoad:false,
			proxy:new Ext.data.HttpProxy({url:Ext.ContextPath+"/salBillVouchList.do", method: 'POST'}),
			reader:new Ext.data.JsonReader({totalProperty:'totalCount',root:"root"},
						[
							{name:'id'},
							{name:'cCusCode',type:'string'},
							{name:'dcreatedate',type:'date',dateFormat:'Y-m-d'},
							{name:'product_id',type:'string'},
							{name:'quantity'},
							{name:'moneySui'},
							{name:'rateUnitPrice'},
							{name:'sheetName',type:'string'},
							{name:'isSpecify'},
							{name:'model',type:'string'},
							{name:'breturnflag'}
						]),
			 remoteSort: true       //是否允许远程排序
		});
		grid_store.on("beforeload",function() {
			grid_store.baseParams['model']=model;
			var sheetName=Ext.fly('sheetName').dom.value;
			//alert(sheetName);
			delete grid_store.baseParams['sheetName'];
			grid_store.baseParams['sheetName']=sheetName;//{params:{start:0,limit:pageSize}}
			grid_store.baseParams['start']=0;
			grid_store.baseParams['limit']=pageSize;

		    //alert(Ext.encode(grid_store.baseParams)); 
		});
		
		var queryBar = new Ext.Toolbar({//其中grid是上边创建的grid容器
		});
		queryBar.add(' ','sheet页:',{xtype:'combo',triggerAction: 'all',valueField:'value',displayField:'name',id:"sheetName",
							  mode:'remote', 
							  store:new Ext.data.SimpleStore({
					              fields:['value','name'],
					              url:Ext.ContextPath+"/sheetNameList.do?model="+model
				        })});
		Ext.getCmp("sheetName").on("select",function(combo,record,index){
			//grid_store.load({params:{sheetName:record.get('value')}});
			grid_store.reload();
		});
		
		queryBar.add('->', {
	        //pressed: false,
	        //enableToggle:false,
	    	id:"delete",
	    	icon :Ext.IconPrefix+'/application_delete.png',
	        text: '删除',
	        cls: '',
	        tooltip:'删除',
	        disabled:false,
	        handler:doDelete//导出excel的处理函数
	    });
		
		queryBar.add('-', {
	        //pressed: false,
	        //enableToggle:false,
	    	id:"clearAll",
	    	icon :Ext.IconPrefix+'/delete.png',
	        text: '清空当前sheet页数据',
	        cls: '',
	        tooltip:'清空当前sheet页数据',
	        disabled:false,
	        handler:clearAll
	    });
	    
	    queryBar.add('-', {
	        //pressed: false,
	        //enableToggle:false,
	    	id:"import",
	    	icon :Ext.IconPrefix+'/database_go.png',
	        text: '导入到用友',
	        cls: '',
	        tooltip:'导入到用友',
	        disabled:false,
	        handler:doDbToUF//导出excel的处理函数
	    });
		
		 //在底部上增加分页信息
	    var paging = new Ext.PagingToolbar({
	    	store: grid_store, 
	        pageSize: pageSize,
	        plugins:new Ext.ux.PageSizePlugin(),
	        displayInfo: true,
	        displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
	        emptyMsg: "没有记录"
	         
	    });
	    var grid = new Ext.grid.EditorGridPanel({
	        id: 'accountManager_EditorGridPanel',
	        stateful:true,
	        //autoHeight: true,
	        //split : true,//边框可以移动
	        loadMask:true,//加载时出现遮罩层
	        stripeRows:true,//斑马线的效果
	        store: grid_store,
	        clicksToEdit: 1,//单击就出现更改状态
	        columnLines:true,
	        cm: cm,
	        disabled:true,
	        sm:new Ext.grid.RowSelectionModel({singleSelect:true}),//单行选择,改为false，就可以多行选择，EditorGridPanel默认是单元格选择
	       // tbar:queryBar,
	        bbar:paging,
	        tbar:queryBar,
	        viewConfig:{
	        	columnsText:'显示的列',
	        	sortAscText:'升序',
	        	sortDescText:'降序',
	        	scrollOffset:25,//右侧滚动条预留的宽度，默认是20
	        	forceFit:true
	        } 
	    });
	    
	    grid.on("beforeedit",function(e){
	    	var record =e.record;
	    	//合计行不能编辑
	    	if(record.get('id')=="total"){
	    		return false;
	    	}
	    });
	    
	    grid.on("afteredit", function(e){
	    	//alert(111);
	    	var record =e.record;
	    	var field =e.field;
	    	var value =e.value;
	    	var originalValue =e.originalValue ;
	    	var rowIndex =e.row;
	    	var columnIndex=e.column;
	    	
	    	var isUpdate=true;
	    	Ext.MessageBox.confirm('消息', '确认要修改吗？ ',showResult);
	    	function  showResult(btn)
	        {
	    		if(btn=='no'){
	    			record.reject();
	    			return;
	    		}
	    		
	    		//breturnflag  红蓝发票,如果是数量  就要进行红蓝发票判断 
	    		if(field=='quantity') {
	    			var breturnflag=record.get('breturnflag');
	    			if(breturnflag==0) {//如果全部为正
	    				if(value<0) {
	    					Ext.msg.Alert("错误","这张发票的数量必须全部为正");
	    					return;
	    				}
	    			} else {
	    				if(value>0) {
	    					Ext.msg.Alert("错误","这张发票的数量必须全部为负");
	    					return;
	    				}
	    			}
	    		}
	    		if(field=='dcreatedate'){
	    			value=Ext.util.Format.date(value,'Y-m-d');//.dateRenderer('Y-m-d')
	    		}
	    		
	    		//alert(value);
	    		
	    		//进行后台查询
				Ext.Ajax.request({
				     method : 'POST',                             
				     url: Ext.ContextPath+'/updateSaleBillVouch.do?field='+field+"&value="+value,  
				     params:record.data,//{id:record.get("id"),field:field,value:value},
				     success:function(request){                   
					       var message = request.responseText;  //取得从JSP文件out.print(...)传来的文本
					       //Ext.Msg.alert('信息',message);        //弹出对话框
					       //record.commit();
					       var obj=Ext.decode(message);
					       if(!obj.success){
					       	  Ext.Msg.alert("消息","后台发生错误，请重试！");
					       	  record.reject();
					       }
					       if(field=='quantity' || field=='moneySui'){
					       	  record.set('rateUnitPrice',obj.rateUnitPrice);
					       }
					       
					       record.commit();
				     },
				     failure:function(){                          //发送失败的回调函数
				       	Ext.Msg.alert("错误", "与后台联系的时候出现了问题");
				       	record.reject();
				     }
				});  		
	        }
	    
	    });
	    
	    
	    //删除处理函数
		function doDelete(button, e){
	        var record = grid.getSelectionModel().getSelected();//获取选择的行
	        if(record){
	        	Ext.MessageBox.confirm('消息', '你真的确定要删除这一行吗？' , doDelete2);	
	        }
	        else {
	        	Ext.MessageBox.alert('消息', '请选择一行！');
	        }
	        //内部函数
	        function doDelete2(btn) {//提示框的值，btn是你选择的按钮，yes或no
	        	if('no'==btn) {//选择不删除，就返回
	        		return;
	        	}
	
	        	
	        	Ext.Ajax.request({
		    		waitTitle:"请稍候",
		    		method:'POST',
		    		url:Ext.ContextPath+'/deleteSaleBillVouch.do',
		    		params:'id='+record.id,
		    		disableChing:false,
		    		autoAbort:false,
		    		success:function(response,options){		
		                        var obj= Ext.decode(response.responseText) ;
		                        if(obj.success==false) {//没有删除成功的时候
		                        	Ext.Msg.alert('信息',"后台发生错误");
		                        	return;
		                        } else {					
		                        	grid_store.remove(record);//在页面上删除数据
		                        	grid.getView().refresh();//重新显示行号，否则会出现行号，断码
		                        } 
		                        
		            },
		            failure:function(response,options){//链接不上服务器的时候报的错误
		                Ext.Msg.alert("修改错误", "与后台联系的时候出现了问题");
		            }
	    	});
	        }    	
	    }
	    

		function clearAll(button, e){
	
	        Ext.MessageBox.confirm('消息', '你真的确定要清除所有数据吗？' , doDelete2);	
	       
	        //内部函数
	        function doDelete2(btn) {//提示框的值，btn是你选择的按钮，yes或no
	        	if('no'==btn) {//选择不删除，就返回
	        		return;
	        	}
	        	grid.setDisabled(true);
				var sheetName=Ext.fly('sheetName').dom.value;
	        	Ext.Ajax.request({
		    		waitTitle:"请稍候",
		    		method:'POST',
		    		url:Ext.ContextPath+'/clearAll.do',
		    		params:{model:model,sheetName:sheetName},
		    		disableChing:false,
		    		autoAbort:false,
		    		success:function(response,options){		
		                        var obj= Ext.decode(response.responseText) ;
		                        if(obj.success==false) {//没有删除成功的时候
		                        	Ext.Msg.alert('信息',"后台发生错误");
		                        	return;
		                        } else {
									grid_store.reload();
									
//									if(win){
//										win.show();
//										win.form.getForm().reset();
//									} else {
//										win=createUploadForm();
//										
//									}
									grid.setDisabled(true);
									//跳出输入文件的框
									task.interval=20000;
									taskRunner.start(task);

		                        }   
		                        grid.setDisabled(false);
		            },
		            failure:function(response,options){//链接不上服务器的时候报的错误
		                Ext.Msg.alert("修改错误", "与后台联系的时候出现了问题");
		            }
	    	});
	        }    	
	    }
	    //导到用友数据库中
	    function doDbToUF() {
	    	Ext.MessageBox.confirm('消息', '你确定要导到用友数据库中吗？' , doDBToUF2);	
	       
	        //内部函数
	        function doDBToUF2(btn) {//提示框的值，btn是你选择的按钮，yes或no
	        	if('no'==btn) {//选择不删除，就返回
	        		return;
	        	}
	        	
	        	//跳出一个时间区间的选择框{startDate:aaaa,endDate:bbbbb}
	        	createDateRegion();
	        }   
	        
	        //弄一个时间区间，并传到后台
	        function createDateRegion() {
	        	  var fp = new Ext.FormPanel({
	      	        width: 200,
	      	        frame: true,
	      	        //title: 'File Upload Form',
	      	        autoHeight: true,
	      	        bodyStyle: 'padding: 10px 10px 0 0px;',
	      	        labelWidth: 90,

	      	        labelAlign:'right',
	      	        defaults: {
	      	            //anchor: '95%',
	      	            allowBlank: false
	      	            //msgTarget: 'side'
	      	        },
	      	        items: [
							 {
							    fieldLabel: '开始日期',
							    name: 'startDate',
							    id: 'startDate',
							    xtype:'datefield',
							    format: 'Y-m-d',
							    vtype: 'daterange',
							    endDateField: 'endDate' // id of the end date field
							  },{
							    fieldLabel: '结束日期',
							    name: 'endDate',
							    id: 'endDate',
							    xtype:'datefield',
							    format: 'Y-m-d',
							    vtype: 'daterange',
							    startDateField: 'startDate' // id of the start date field
							  }		      	                
	      	        	],
	      	        buttons: [{
	      	            text: '确定',
	      	            handler: function(){
	      	                if(fp.getForm().isValid()){     	
	      	                	//获取开始日期和结束日期的值
	      	                	//fp.findById("startDate").getValue()
	      	                	//alert(fp.findById("startDate").getValue());
	      	                	var aob= {startDate:fp.findById("startDate").getRawValue(),endDate:fp.findById("endDate").getRawValue()};
	      	                	dateRegionWin.close();
	      	                	createAJAXTODB(aob);
	      	                }
	      	            }
	      	        },{
	      	            text: '重置',
	      	            handler: function(){
	      	                fp.getForm().reset();
	      	            }
	      	        }]
	      	    });
	      	    
	      	    var dateRegionWin=new Ext.Window({
	      	    	layout:'fit',
	      	    	width: 300,
	      	    	height:140,
	      	    	closeAction:'close',
	      	    	closable:true,
	      	    	maximizable:false,
	      	    	minimizable:false,
	      	    	title:'选择时间区间',
	      	    	//x:50,
	      	    	y:50,
	      	    	items:[fp]	
	      	    });

	      	    dateRegionWin.show();
	        }
	        //发送请求道后台
	        function createAJAXTODB(aob) {
	        	grid.setDisabled(true);
	        	Ext.MessageBox.wait("正在把数据导入到用友的数据库中......", "请等待");   
	        	//Ext.MessageBox.wait('请等待','正在把数据导入到用友的数据库中......');
//	        		{
//					title: '请等待',
//					msg: '正在把数据导入到用友的数据库中......',
//					width:300,
//					//progress:true,
//					closable:false
//				});
				var sheetName=Ext.fly('sheetName').dom.value;
	        	Ext.Ajax.request({
		    		waitTitle:"请稍候",
		    		method:'POST',
		    		url:Ext.ContextPath+'/dbToUF.do',
		    		params:{model:model,sheetName:sheetName,startDate:aob.startDate,endDate:aob.endDate},
		    		disableChing:false,
		    		autoAbort:false,
		    		timeout:6000000,
		    		success:function(response,options){		
		                        var obj= Ext.decode(response.responseText) ;
		                        if(obj.success==false) {//没有删除成功的时候
		                        	
		                        	Ext.Msg.alert('信息',obj.errors.msg,refesh);
		                        	//return;
		                        } else {
									Ext.MessageBox.hide();
									Ext.Msg.alert("消息","导入成功！",refesh);
									//alert('导入成功！');
		                        }

		            },
		            failure:function(response,options){//链接不上服务器的时候报的错误
		                Ext.Msg.alert("消息", "导入时间较长，请稍后刷新页面!");
		                //grid.setDisabled(false);
		            	 //Ext.Msg.hide();
		            }
	    		});
	    		 function refesh(){
		                        	 //grid.setDisabled(false);
					                //grid.getStore().reload();
					                location.reload(); 
					                //grid.getView().refresh();
		         }
	        }
	    	
	    }
	    
	    return grid;
    }

    var grid= createGrid();
    //var uploadfForm=createUploadForm();
    var viewport = new Ext.Viewport({
        	id:"conten_viewport",
        	frame : false,
			border : false,
			lines : false,
            layout: 'fit',
            items: [grid]
    });
    

});